<?php
class messege_model extends CI_Model
{
	var $data;
	
	function __construct()
	{
		parent::__construct();
		$config['hostname'] = 'localhost';
		$config['username'] = 'root';
		$config['password'] = '';
		$config['database'] = 'helloworld';
		$config['dbdriver'] = 'mysql';
		$config['dbprefix'] = '';
		$config['pconnect'] = TRUE;
		$config['db_debug'] = TRUE;
		$config['cache_on'] = FALSE;
		$config['cachedir'] = '';
		$config['char_set'] = 'utf8';
		$config['dbcollat'] = 'utf8_general_ci';
		$config['swap_pre'] = '';
		$config['autoinit'] = TRUE;
		$config['stricton'] = FALSE;
		//@@@@@@testers: check the database name before start!!
		$this->load->database($config);
		$table_name='messege';
	}
	
	function get_all_messege()
	{
		$userid=$this->session->userdata('userid');
		$sql="select * " .
			 "from messege, user " .
			 "where (messege.senderid=user.userid) and" .
			 "(senderid = ? or receiverid = ?)" .
			 "  order by messegeid desc" .
			 " limit 0 , 5";
		return $this->db->query($sql, array($userid, $userid));
	}
	function get_messege($s)
	{
		$f_ownerid=$this->session->userdata('userid');
		$s_ownerid=$s;
		$sql="select * " .
			 "from messege, user " .
			 "where (messege.senderid=user.userid)  ".
			 "and ( (senderid = ? and receiverid = ?) or (senderid = ? and receiverid = ?))" .
			 "order by messegeid desc " .
			 "limit 0 , 5";
		
		return $this->db->query($sql, array($f_ownerid, $s_ownerid, $s_ownerid, $f_ownerid));
		
	}
	function create_messege($id, $text)
	{
		$senderid=$this->session->userdata('userid');
		$sender_name=$this->session->userdata('fullname');
		
		$receiverid=$id;
		$content=$text;
		
		//opt
		$this->db->from('user');
		$this->db->where('userid', $receiverid);
		$q = $this->db->get();
		$receiver=$q->result();
		$receiver_name=$receiver[0]->fullname;
		
		$new_messege['senderid']=$senderid;
		$new_messege['receiverid']=$receiverid;
		$new_messege['sender_name']=$sender_name;
		$new_messege['receiver_name']=$receiver_name;
		$new_messege['content']=$content;
		$this->db->insert('messege',$new_messege);
		
	}
	
	function ChangeQueryResultToArray($query)
	{
		if($query->num_rows() > 0)
		{
			foreach ($query->result() as $row)
			{
				$data[] = $row;
			}
			return $data;
		}
	}
}
	

